package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.AssetType;
import com.neusoft.neuiotms.dcam.fixed.model.QAssetType;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedAssetTypeRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAssetTypeRepositoryImpl extends AbstractRepository
        implements CustomizedAssetTypeRepository {

    @Override
    public Page<AssetType> search(final Pageable pageable, final Searchable searchable) {
        final QAssetType qAssetType = QAssetType.assetType;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AssetType> query = this.query().selectFrom(qAssetType);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAssetType qAssetType = QAssetType.assetType;

        where.and(super.containsStr(qAssetType.name, searchable, "name"));
        where.and(super.containsStr(qAssetType.code, searchable, "code"));
        where.and(super.containsStr(qAssetType.parent.name, searchable, "parentName"));
        final String[] codes = searchable.getStrArray("codes");
        if (codes != null && codes.length > 0) {
            where.and(super.inStrings(qAssetType.code, searchable, "codes"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("parentId"))) {
            where.and(super.equalsLong(qAssetType.parent.id, searchable, "parentId"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("parentCode"))) {
            where.and(super.equalsStr(qAssetType.parent.code, searchable, "parentCode"));
        }

        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return AssetType.class;
    }

}
